package com.joy.common.interceptor;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Description 判断是否拥有权限进行此操作
 * @Author yjzhao
 * @Date 2019/9/27 20:28
 **/
@Slf4j
@Component
public class PermissionInterceptor extends HandlerInterceptorAdapter {

	@Override
	public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView mav) throws Exception {


	}

	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response,
							 Object handler) throws Exception {
		String requestURI = request.getRequestURI();

		if (StrUtil.isEmpty(requestURI) || "/".equals(requestURI)) {
			return super.preHandle(request, response, handler);
		}
		log.info("requestURI:{}", requestURI);
		RequestMapping annotation = null;
		if (handler instanceof HandlerMethod) {
			HandlerMethod h = (HandlerMethod) handler;
			annotation = h.getMethod().getDeclaringClass().getAnnotation(RequestMapping.class);
			String[] value = annotation.value();
			if (value.length > 0) {
				request.setAttribute("ctlKey", value[0]);
			}

			String paramString = "";
			String method = h.getMethod().getName();
			if ("index".equals(method)) {
				paramString = "menu:" + requestURI.replaceFirst("/", "").replace("/", ":");
			} else {
				paramString = requestURI.replaceFirst("/", "").replace("/", ":");
			}
			Subject subject = SecurityUtils.getSubject();
			subject.checkPermission(paramString);
		}
		return super.preHandle(request, response, handler);
	}
}
